package com.bibi.zoo.service;

import com.bibi.zoo.pkg.resp.BaseResp;
import com.bibi.zoo.pkg.resp.RespCheckGame;
import com.bibi.zoo.web.req.ReqInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class DogTaskService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private HandleService handleService;
    ExecutorService pool = Executors.newCachedThreadPool();
    @Resource
    private RestTemplate restTemplate;
    /**
     * 动物id
     */
    int aid = 4;

    private String phone = "13063695912";
    private String pwd = "601382xu";

    @Scheduled(cron = "0 47 15 * * ?")
    public void loginTask() {
        logger.info("开启登录任务");
        Constants.luckkeyMap.removeAll(phone);
        ReqInput req = new ReqInput();
        req.setPhone(phone);
        req.setPwd(pwd);
        while (Constants.luckkeyMap.get(phone).size() < 10) {
            handleService.getLuckkey(req);
        }
    }

    @Scheduled(cron = "0 53 15 * * ?")
    public void buyTask() throws InterruptedException {
        logger.info("开启抢购任务");
        CountDownLatch countDownLatch = new CountDownLatch(1);
        asynBuy(countDownLatch);
        RespCheckGame respCheckGame = null;
        while (respCheckGame == null) {
            respCheckGame = handleService.checkGame(phone);
        }
        long time = respCheckGame.getData().getTime();
        if(time > 0) {
            Thread.sleep(time * 1000);
//            Thread.sleep(5000);
        }
        countDownLatch.countDown();
    }
    private void asynBuy(CountDownLatch countDownLatch) {
        List<String> keys = Constants.luckkeyMap.get(phone);
        long shold = 500;
        for(int i=0;i<keys.size();i++) {
            String luckkey = keys.get(i);
            pool.execute(() -> {
                HttpHeaders authHeaders = new HttpHeaders();
                authHeaders.add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36");
                authHeaders.add("luckkey",luckkey);
                authHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
                HttpEntity<String> requestEntity2 = new HttpEntity<>(null, authHeaders);
                Map<String,Object> params = new HashMap<>();
                params.put("id", aid);
                try {
                    logger.info("{}进入抢购阻塞",luckkey);
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for(int j=0;j<30;j++) {
                    long start = System.currentTimeMillis();
                    try{
                        BaseResp baseResp = restTemplate.postForObject("http://luck9.luckyzodiac12.com/api/game/flash_buy/{id}", requestEntity2, BaseResp.class,params);
                        logger.info("phone:{},抢购结果：{}", phone,com.alibaba.fastjson.JSONObject.toJSONString(baseResp));
                    } catch (Exception e) {
                        logger.error(e.getMessage());
                    }
                    long end = System.currentTimeMillis();
                    long wait = shold-(end - start);
                    if(wait > 0) {
                        try {
                            if(wait > 50) {
                                wait = wait + new Random().nextInt(100) - 50;
                            }
                            Thread.sleep(wait);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        try {
                            Thread.sleep(new Random().nextInt(50));
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
        pool.execute(() -> {
            HttpHeaders authHeaders = new HttpHeaders();
            authHeaders.add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36");
            authHeaders.add("luckkey",keys.get(0));
            authHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<String> requestEntity2 = new HttpEntity<>(null, authHeaders);
            Map<String,Object> params = new HashMap<>();
            params.put("id", aid);
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for(int j=0; j<200; j++) {
                long start = System.currentTimeMillis();
                try {
                    ResponseEntity<BaseResp> exchange = restTemplate.exchange("http://luck9.luckyzodiac12.com/api/game/checkOpen/{id}", HttpMethod.GET, requestEntity2, BaseResp.class, params);
                    logger.info("phone:{},开奖结果:{}",phone,com.alibaba.fastjson.JSONObject.toJSONString(exchange.getBody()));
                } catch (Exception e) {
                    logger.error(e.getMessage());
                }
                long end = System.currentTimeMillis();
                long wait = 2000 - (end - start);
                if(wait > 0) {
                    try {
                        Thread.sleep(wait);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}
